package gupao.concurrency.lock;

import gupao.concurrency.threads.Utils;
import lombok.extern.slf4j.Slf4j;
import org.openjdk.jol.info.ClassLayout;

import java.util.concurrent.CountDownLatch;

@Slf4j
public class SynchronizedReentryAndNonShared {

    static boolean printMarkword = false;

    static Object obj = new Object();

    public static void main(String[] args) throws InterruptedException {
        testReentrantAndNonShared();
    }

    static void testReentrantAndNonShared() throws InterruptedException {
//        SynchronizedSample sample = new SynchronizedSample();
        SynchronizedSample sample = new SynchronizedSub();
        Thread t1 = new Thread(() -> {
            log.info("start running to call doBiz1");
            sample.doBiz1(2000);
        });
        Thread t2 = new Thread(() -> {
            log.info("start running to call doBiz1");
            sample.doBiz1(500);
        });
        t1.start();
        t2.start();
        t1.join();
        t2.join();
        log.info("out of sync");
        if (printMarkword) {
            System.out.println(ClassLayout.parseInstance(sample).toPrintable());
        }
    }

    static
    class SynchronizedSub extends SynchronizedSample {
        public synchronized void doBiz1(long timeCost) {
            super.doBiz1(timeCost);
        }
    }


    static
    class SynchronizedSample {
        public synchronized void doBiz1(long timeCost) {
            log.info("do biz 1");
            if (printMarkword) {
                System.out.println(ClassLayout.parseInstance(this).toPrintable());
                System.out.println();
            }
            Utils.sleepIgnoreExp(timeCost);
            doBiz2(timeCost);
        }

        public synchronized void doBiz2(long timeCost) {
            log.info("do biz 2");
            if (printMarkword) {
                System.out.println(ClassLayout.parseInstance(this).toPrintable());
                System.out.println();
            }
            Utils.sleepIgnoreExp(timeCost);
            doBiz3(timeCost);
        }

        public synchronized void doBiz3(long timeCost) {
            log.info("do biz 3");
            Utils.sleepIgnoreExp(timeCost);
            if (printMarkword) {
                System.out.println(ClassLayout.parseInstance(this).toPrintable());
                System.out.println();
            }
        }
    }
}
